package aaaBrowser.semeDemo;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;

import org.junit.*;

import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.*;

import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.openqa.selenium.support.ui.Select;

import com.attilax.core;
import com.attilax.collection.CollX;
import com.attilax.io.filex;
import com.attilax.io.pathx;
import com.attilax.laisens.LaisensManger;
import com.attilax.laisens.OverTimeEx;
import com.attilax.util.CstGettor;
import com.attilax.util.PropX;
import com.google.common.collect.Lists;
import com.thoughtworks.selenium.Selenium;
import com.thoughtworks.selenium.webdriven.WebDriverBackedSelenium;

@SuppressWarnings("all")
public class SelemAti_firefox_demoGui {

	private boolean acceptNextAlert = true;
	private StringBuffer verificationErrors = new StringBuffer();
	static Map<String, String> PropMap = new ConcurrentHashMap();
	// private RemoteWebDriver driver;
	// public static
	static PropX px;
	private static String proxy;

	/**
	 * aaaClicker.SelemAti
	 * 
	 * @param args
	 */

	public static void main(String[] args) {
		System.out.println("..");
		// try {
		// LaisensManger
		// .checkOvertime("2016-07-13", CstGettor.getDateFrmNet());
		// } catch (OverTimeEx e2) {
		// // TODO Auto-generated catch block
		// e2.printStackTrace();
		// throw new RuntimeException(e2);
		// }
		// 59.58.162.141:888 111.12.251.199:80
		proxy = "59.58.162.141:888";
		Map mp = new HashMap();
		List<String> li = Lists.newArrayList(proxy);
		// filex.read2list_filtEmptyNstartSpace(pathx .classPathParent() +
		// "\\proxy.txt");

		// px = new PropX(pathx.classPathParent() + "\\click.txt", "utf-8");
		// px.setValue(
		// PropMap,
		// "start,end,showimg,proxy,title,per_invoke_sleep,per_timeout,pageload_timeout,baseUrl,ScriptTimeout");
		PropMap.put("start", "0");
		PropMap.put("end", "1");
		PropMap.put("proxy", "1");
		PropMap.put("click_aft_sleep", "500");
		PropMap.put("showimg", "1");
		PropMap.put("per_invoke_sleep", "10");PropMap.put("per_timeout", "30");PropMap.put("pageload_timeout", "30");PropMap.put("ScriptTimeout", "30");
		
		
		
		

		// p916
		if (PropMap.get("proxy").equals("0")) {

			try {
				int maxOpenCountNoProxy = 1;
				maxOpenCountNoProxy = Integer.parseInt(System
						.getProperty("ati.maxOpenCountNoProxy"));
				li = CollX.geneItems(maxOpenCountNoProxy);
			} catch (Exception e) {
				li = CollX.geneItems(300);
			}

		}// end p916
		final List<String> li2 = li;
		int start = Integer.parseInt(PropMap.get("start"));
		int end = Integer.parseInt(PropMap.get("end"));
		for (int i = start; i < end; i++) {
			final int j = i;
			core.execMeth_Ays(new Runnable() {

				@Override
				public void run() {
					single(li2, j);

				}
			}, "--threadName" + String.valueOf(i));
			try {
				Thread.sleep(Integer.parseInt(PropMap.get("per_invoke_sleep")));
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}
		System.out.println("--f");
		while (true) {
			try {
				Thread.sleep(5000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		// System.out.println("--f");

	}

	private static void single(List<String> li, int i) {
		WebDriver driver = null;
		Selenium selenium;
		// PropX px = new PropX(pathx.classPathParent() +
		// "\\click.txt","utf-8");
		try {
			System.out.println("---cur start:" + String.valueOf(i));
			FirefoxProfile profile = new FirefoxProfile();
			try {
				if (PropMap.get("proxy").equals("1")) {
					// System.out.println();
					// 使用代理
					profile.setPreference("network.proxy.type", 1);
					// http协议代理配置
					String proxStr = li.get(i).trim();
					System.out.println("--use prox:" + proxStr);
					String[] prx = proxStr.split(":");
					profile.setPreference("network.proxy.http", prx[0].trim());
					profile.setPreference("network.proxy.http_port",
							Integer.parseInt(prx[1].trim()));
					// 对于localhost的不用代理，这里必须要配置，否则无法和webdriver通讯
					profile.setPreference("network.proxy.no_proxies_on",
							"localhost");
				}

				Proxy proxy = new Proxy(); // jeig proxy only for ie
			} catch (Exception e) {
				// TODO: handle exception
			}
			System.out.println(" show img is :" + PropMap.get("showimg"));
			if (PropMap.get("showimg").equals("0")) {

				profile.setPreference("permissions.default.image", 2);// no img
			}
			pathx.isWebPathMode=true;
			System.setProperty("webdriver.firefox.bin", pathx.classPathParent()
					+ "\\Mozilla Firefox\\firefox.exe");

			driver = new FirefoxDriver(profile);
			// driver = new FirefoxDriver(profile);
			// String proxyStr=li.get(i);
			// proxy.setHttpProxy(proxyStr);
			// profile.set
			// seleniu

			// 第三种全部删除
			// driver.manage().deleteAllCookies();
			// driver.d
			// WebDriver driver;
			String baseUrl;
			// driver = new FirefoxDriver();
			baseUrl = "http://www.ip138.com/";
			// baseUrl = PropMap.get("baseUrl").trim();
			// baseUrl="http://atidestoon.com/getcookie.php";
			// selenium = new WebDriverBackedSelenium(driver, baseUrl);
			// selenium.deleteAllVisibleCookies();
			System.out.println("  will open url:" + baseUrl + " idx:"
					+ String.valueOf(i));
			driver.manage()
					.timeouts()
					.implicitlyWait(
							Integer.parseInt(PropMap.get("per_timeout")),
							TimeUnit.SECONDS);
			driver.manage()
					.timeouts()
					.pageLoadTimeout(
							Integer.parseInt(PropMap.get("pageload_timeout")),
							TimeUnit.SECONDS);

			try {
				driver.manage()
						.timeouts()
						.setScriptTimeout(
								Integer.parseInt(PropMap.get("ScriptTimeout")),
								TimeUnit.SECONDS);
			} catch (Exception e) {
				// TODO: handle exception
			}

			// driver.manage()
			// .timeouts().
			System.out.println("implicitlyWaitt" + String.valueOf(i));

			//
			try {
				driver.get(baseUrl + "");
			} catch (TimeoutException e) {
				System.out.println("----driver.get TimeoutException:"
						+ e.getMessage());
			}

			System.out.println(" get(baseUrl " + String.valueOf(i));
			// 定位到所有<input>标签的元素，然后输出他们的id
			System.out.println("scan a start" + String.valueOf(i));
			// String string = "百搭欧简约时尚单肩大包手提包包";

			// String tits = PropMap.get("title");
			// String[] tit_a = tits.split(",");
			// for (String string : tit_a) {
			//
			// try {
			// System.out.println("--start click url:" + string);
			// driver.findElement(By.linkText(string.trim())).click();
			// } catch (Exception e) {
			// e.printStackTrace();
			// }
			// }

			//
			// List<WebElement> element = driver.findElements(By.tagName("a"));

			// for (WebElement e : element) {
			// System.out.println(e.toString());
			// if (e.getAttribute("href").startsWith(
			// "http://out.zhe800.com/guang/p/deal/100040878")) {
			// System.out.println(e.getAttribute("href"));
			// e.click();
			//
			// break;
			// }
			//
			// }
			System.out.println("scan a end" + String.valueOf(i));
			// String js = filex
			// .read(pathx.classPath(ClickX.class) + "\\login.js");
			// ((JavascriptExecutor) driver).executeScript(js);
			// 第三种全部删除
			// driver.manage().deleteAllCookies();
			int click_aft = 20;
			try {
				click_aft = Integer.parseInt(PropMap.get("click_aft_sleep"));
			} catch (Exception e) {
				e.printStackTrace();
			}
			try {

				Thread.sleep(click_aft * 1000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (driver != null)
				driver.quit();
			System.out.println("---cur finish:" + String.valueOf(i));
		}

	}

	@Before
	public void setUp() throws Exception {

	}

	@Test
	public void testSelemAti() throws Exception {

		// driver.findElement(By.id("kw")).click();
		// driver.findElement(By.id("kw")).clear();
		// driver.findElement(By.id("kw")).sendKeys("attilax");
		// driver.findElement(By.id("su")).click();
	}

	// @ After
	public void tearDown() throws Exception {
		// driver.quit();
		String verificationErrorString = verificationErrors.toString();
		if (!"".equals(verificationErrorString)) {
			fail(verificationErrorString);
		}
	}

	private boolean isElementPresent(By by) {
		try {
			// driver.findElement(by);
			return true;
		} catch (NoSuchElementException e) {
			return false;
		}
	}

	private boolean isAlertPresent() {
		try {
			// driver.switchTo().alert();
			return true;
		} catch (NoAlertPresentException e) {
			return false;
		}
	}

	private String closeAlertAndGetItsText() {
		return null;
		// try {
		// Alert alert = driver.switchTo().alert();
		// String alertText = alert.getText();
		// if (acceptNextAlert) {
		// alert.accept();
		// } else {
		// alert.dismiss();
		// }
		// return alertText;
		// } finally {
		// acceptNextAlert = true;
		// }
	}
}
